-module(user_adapter).
-export([addchange/1,get/2,del/1,auth/2,ui_identity/1,get/1,assign/1,check_user/1,toHtml/2,update_login/2,getLoginedInfo/2]).
-include("rec_dec.hrl").
-include("yaws_api.hrl").
addchange(L) ->
	User = 
		case list_to_binary(tools:get_param(L,"user_id","")) of
		<<"">> ->
			#user_rec{
				id = <<"">>};
		Id ->
			case user_service:get({id,Id}) of
			[] ->
				undefined;
			[U] ->
				U;
			_ ->
				undefined
			end
		end,
	if
		is_record(User,user_rec) ->
			Res = user_service:addchange(User#user_rec{
				login_name = tools:get_param(L,"login_name",""),
				name = tools:get_param(L,"name",""),
				phone = tools:get_param(L,"phone",""),
				mail= tools:get_param(L,"mail",""),
				im= tools:get_param(L,"im",""),
				register_id= case User#user_rec.id of
					<<"">> ->
						session_service:getLoginedInfo(L,user_id);
					_ ->
						User#user_rec.register_id
					end,
				password = case id of 
				<<"">> ->
					tools:get_param(L,"password",login_name);
				_ ->
					password
				end
			}),
			Vendor_Id = tools:get_param(L,"vendor_id",""),
			if
				Vendor_Id =/= "", User#user_rec.id =:= <<"">> ->
					user_service:addchange(#user_vendor_rec{
						v_id = list_to_binary(Vendor_Id),
						u_id = (Res#user_rec.id),
						created_date = calendar:local_time()
					});
				true ->
					ok
			end,
					
			{html,rfc4627:encode(tojson(Res))};
		true ->
			{html,"error data"}		
	end.
assign(L) ->
	VendorId = list_to_binary(tools:get_param(L,"vendor_id","")),
	UserId = list_to_binary(tools:get_param(L,"user_id","")),
	Stat = tools:get_param(L,"stat","0"),
	{html,
	 case {VendorId,Stat} of 
	 {"",_} ->
		"{\"result\":\"error\"}";
	 {_,"1"} ->
		user_service:addchange(#user_vendor_rec{
			v_id = (VendorId),
			u_id = (UserId),
			created_date = calendar:local_time()
		}),
		"OK";
	{_,"0"} ->
		user_service:del(user_vendor_rel,{VendorId,UserId}),
		"{\"result\":\"ok\"}"
	 end
	}.
del(L) ->
	{"id",Id} = lists:keyfind("id",1,L),
	{html,
	case Id of
	"" ->
		"{\"result\":\"miss id\"}";
	_ ->
		user_service:del(user,list_to_binary(Id)),
		"{\"result\":\"ok\"}"
	end
	}.
	
get(L) ->
	LoginRec = session_service:getLoginRec(
		tools:get_param(L,"_inter_session_id","undefined")
	),
	case {LoginRec#login_rec.mode,LoginRec#login_rec.user_id,tools:get_param(L,"vendor_id","")} of
	{admin,User_Id,""} ->
		user_service:get({register_id,User_Id});
	{admin,_,VendorId} ->
		user_service:get({vendor_id,list_to_binary(VendorId)});
	{user,User_Id,_} ->
		user_service:get({id,User_Id});
	_ ->
		[]
	end.
	
get(json,L)	->	
	J_Objs = lists:map(fun(E) ->
					tojson(E)
                end,
                user_adapter:get(L)),
	rfc4627:encode({obj,[{"aaData",J_Objs}]});
get(login_rec,L) ->
	lists:map(fun(E) ->
				case E#login_rec.mode of
				admin ->
					{E,"系统管理"};
				user ->
					{E,io_lib:format("系统操作:~s",[E#login_rec.vendor_name])}
			    end
			  end,
			user_service:get({login_rec,list_to_binary(tools:get_param(L,"user_id",""))})
	);
	
get(entity,User_Id) ->
	case list_to_binary(User_Id) of
	<<"">> ->
		#user_rec{
				id = <<"">>,
				name = "",
				login_name = "",
				phone = "",
				im = ""};
	UId ->
		[U|_] = user_service:get({id,UId}),
		U
	end;
get(html_table,L) ->
	{ehtml,{'table',[],
		lists:map(
			fun({E,T}) ->
				toHtml(table_rec,{E,T})
			end,
			user_adapter:get(L)
		)
		}};
	
get(html_list,L) ->
	{ehtml,lists:map(
						fun(E) ->
							toHtml(list,E)
						end,
						user_adapter:get(L))
	}.
tojson(Name,undefined) ->
	{Name,""};
tojson(Name,Value) when is_binary(Value) ->
	{Name,Value};
tojson(Name,Value) when is_list(Value) ->
	{Name,list_to_binary(Value)};
tojson(Name,Value) ->
	{Name,Value}.
	
tojson(E) when is_record(E,user_rec) ->
	{obj,
		[
			tojson("name",E#user_rec.name)
            ,tojson("login_name",E#user_rec.login_name)
            ,tojson("password",E#user_rec.password)
            ,tojson("phone",E#user_rec.phone)
            ,tojson("mail",E#user_rec.mail)
			,tojson("im",E#user_rec.im)
			,tojson("id",E#user_rec.id)
			,tojson("vendor_name","undefined")
        ]
    }.
toHtml(edit,{E,FormName}) when is_record(E,user_rec) ->
   {'div',[],[
		{form,[{id,FormName},{action,"/www/queue_act.yaws?mod=user&action=addchange"},{method,"get"}],
              [
			   {input,[{name,"user_id"},{'id',"user_id"},{value,binary_to_list(E#user_rec.id)},{type,"hidden"}],[]},
			   {table,[],[
			   		{tr,[],[{td,[],"登录名称"},{td,[],[{input,[{'name',"login_name"},{'id',"login_name"},{'value',E#user_rec.login_name}],[]}]}]},
			   		{tr,[],[{td,[],"姓名"},{td,[],[{input,[{'name',"name"},{'value',E#user_rec.name}],[]}]}]},
			   		{tr,[],[{td,[],"联系电话"},{td,[],[{input,[{'name',"phone"},{'id',"phone"},{'value',E#user_rec.phone}],[]}]}]},
			   		{tr,[],[{td,[],"IM"},{td,[],[{input,[{'name',"im"},{'value',E#user_rec.im}],[]}]}]}
			  		]
			  	}
			  ]
		}
	]};
toHtml(edit,E) when is_record(E,user_rec) ->
	toHtml(edit,{E,"user_form"});
			  
toHtml(table_rec,{E,Assigned}) when is_record(E,user_rec) ->
	io:format("dump ~p as ~p",[E,Assigned]),
	{'tr',[],[
		{td,[],E#user_rec.login_name},
		{td,[],E#user_rec.name},
		{td,[],E#user_rec.phone},
		{td,[],[{
			input,case Assigned of 
				  false -> 
					[{type,"checkbox"},{class,"user_assigned"},{id,binary_to_list(E#user_rec.id)}];
				  true -> 
					[{type,"checkbox"},{class,"user_assigned"},{id,binary_to_list(E#user_rec.id)},{checked,"true"}]
				  end,
			"选择"
			}]}
	]};
	
toHtml(list,E) when is_record(E,user_rec) ->
	{'div',[{'class',"user list_item"}],[
		{'p',[],[{'a',[{href,io_lib:format("/www/pages/user_page.yaws?user_id=~s",[E#user_rec.id])}],E#user_rec.name}]},
		{'p',[],io_lib:format("登录名称:~s",[E#user_rec.login_name])},
		{'p',[],io_lib:format("电话:~s",[E#user_rec.phone])}
	]}.
update_login(L_Id,{vendor_id,Id}) ->
	io:format("session:~p update the vendor_id with ~p~n",[L_Id,Id]),
 	gen_server:call(session_service,{update,L_Id,{vendor_id,Id}}),
	gen_server:call(session_service,{update,L_Id,{vendor_name,(vendor_service:get(Id))#vendor_rec.name}});
update_login(_,_) ->
	ok.
check_user(L)->
	{html,case 
		case {tools:get_param(L,"mobile",""),tools:get_param(L,"name","")} of
		{"",""} ->
			[];
		{Mobile,""} ->
			check_user(both,Mobile);
		{_,Name} ->
			check_user(both,Name)
		end
	of
	[U] ->
		binary_to_list(U#user_rec.id);
	[] ->
		""
	end}.
check_user(both,Name) ->
	case {user_service:get({name,Name}),user_service:get({phone,Name})} of
	{[],[]} ->
		[];
	{[U1],[]} when is_record(U1,user_rec) ->
		[U1];
	{[],[U2]} when is_record(U2,user_rec) ->
		[U2];
	{[U],[U]} when is_record(U,user_rec) ->
		[U];
	_ ->
		io:format("unexcept user info found , please check user data\n"),
		[]
	end.

auth(operator,L) ->
	Password = tools:get_param(L,"password",""),
	Login_Name = tools:get_param(L,"login_name",""),
	Terminal = tools:get_param(L,"terminal","pc"),
	case tools:get_param(L,"mode","user") of
	"admin" ->
		auth(admin,{Login_Name,Password,Terminal});
	"admin_ajax" ->
		auth(admin_ajax,{Login_Name,Password,Terminal});
	_ ->
		auth(user,{Login_Name,Password,Terminal})
	end;
	
auth(user,{Name, Password,Terminal}) ->
	case check_user(both,Name) of 
	[] ->
		io:format("unknow user name"),
		[{redirect_local,"/www/login.yaws"}];
	[U|_] ->
		{Vendor_Id,Vendor_Name} = case vendor_service:get({managedby_only,U#user_rec.id,U#user_rec.right}) of
		[] ->
			{undefined,"missed"};
		[{V_id,V}] ->
			{V_id,V#vendor_rec.name};
		[V|Vs] ->
			{[V|Vs],undefined}
		end,
		S = #login_rec{login_name = Name,
				password = lisi,
				register_id = (U#user_rec.register_id),
				login_date = calendar:local_time(),
				vendor_name = Vendor_Name,
				vendor_id = Vendor_Id,
				terminal = Terminal,
				user_id = U#user_rec.id,
				mode= user},
		case gen_server:call(session_service,{login,S}) of
		{ok,Id} ->
			Cookie = yaws_api:new_cookie_session(Id),
			[{redirect_local, get_redirect_url(S)},yaws_api:setcookie("bizcookie",Cookie,"/")];
		_ ->
			[{redirect_local,"/www/login.html"}]
		end
	end;
auth(temp_reg,{Mobile,Token}) ->
	case gen_server:call(session_service,{login,S = #login_rec{
		login_name = Mobile,
		user_id = Token
	}}) of
	{ok,Id} ->
		Cookie = yaws_api:new_cookie_session(Id),
		[{html,"ok",yaws_api:setcookie("bizcookie",Cookie,"/")}];
	_ ->
		[{html,"error"}]
	end;

auth(admin_ajax,{Mobile,Password,Type}) ->
	case check_user(both,Mobile) of
	[U] when U#user_rec.right =:= admin ->
		S = #login_rec{login_name = U#user_rec.login_name,
				password = lisi,
				login_date = calendar:local_time(),
				mode = admin,
				state = case Type of 
				first_login ->
					first_login;
				_ ->
					U#user_rec.state
				end,
				register_id = U#user_rec.register_id,
				user_id = U#user_rec.id,
				vendor_id = case vendor_service:get({register,U#user_rec.register_id}) of
							[V|_] ->
								V#vendor_rec.id;
							[] ->
								undefined
							end
			},
		case gen_server:call(session_service,{login,S}) of
		{ok,Id} ->
			Cookie = yaws_api:new_cookie_session(Id),
			[{html,rfc4627:encode({obj,[
										{result,<<"ok">>},
										{url,list_to_binary(get_redirect_url(S))}
									]
								  }
								)
			   },yaws_api:setcookie("bizcookie",Cookie,"/")];
		_ ->
			{html,rfc4627:encode({obj,[{result,<<"系统内部错误，请重试">>}]})}
		end;
	_ ->
		{html,rfc4627:encode({obj,[{result,<<"用户名错误">>}]})}
	end;

	
auth(admin,{Mobile,Password,Type}) ->
	case check_user(both,Mobile) of
	[U] when U#user_rec.right =:= admin ->
		S = #login_rec{login_name = U#user_rec.login_name,
				password = lisi,
				login_date = calendar:local_time(),
				mode = admin,
				state = case Type of 
				first_login ->
					first_login;
				_ ->
					U#user_rec.state
				end,
				register_id = U#user_rec.register_id,
				user_id = U#user_rec.id,
				vendor_id = case vendor_service:get({register,U#user_rec.register_id}) of
							[V|_] ->
								V#vendor_rec.id;
							[] ->
								undefined
							end
			},
		case gen_server:call(session_service,{login,S}) of
		{ok,Id} ->
			Cookie = yaws_api:new_cookie_session(Id),
			io:format("auth ~p~n ok~n",[Mobile]),
			[{redirect_local, get_redirect_url(S)},yaws_api:setcookie("bizcookie",Cookie,"/")];
		_ ->
			io:format("create login session failed\n"),
			[{redirect_local,"/www/login.html"}]
		end;
	_ ->
		io:format("unknow user login to admin with UserName:~s",[Mobile]),
		[{redirect_local,"/www/login.html"}]
	end.
get_redirect_url(S) ->
	case {S#login_rec.mode,S#login_rec.state} of
	{admin,first_login} ->
		"/www/pages/register2.yaws";
	{admin,_} ->
		 case getLoginedInfo(S,vendor_mode) of
		 central_vendor ->
			io:format("redirect url: /www/pages/vendor_mgr.yaws~n"),
		 	"/www/pages/vendor_mgr.yaws";
		 simple_vendor ->
		 	io_lib:format("/www/pages/vendor_page.yaws?vendor_id=~s",[binary_to_list(S#login_rec.vendor_id)])
		 end;
	{user,_} ->
		case S#login_rec.terminal of
		"mobile" ->
			case S#login_rec.vendor_id of
			undefined ->
				io:format("no vendor found"),
				"/mobile/login.html";
			A when is_list(A) ->
				"/mobile/select_vendor.yaws";
			Id ->	
				"/mobile/main/app.yaws"
			end;
		_ ->
			"/www/main.yaws"
		end;
	_ ->
		io:format("unexpected status ~n"),
		 "/www/queue_view.yaws"
	end.
getLoginedInfo(S,vendor_mode) when is_record(S,login_rec) ->
	case {S#login_rec.user_id,S#login_rec.vendor_id,S#login_rec.mode} of
	{Id,Id,admin} ->
		simple_vendor;
	{_,_,user} ->
		user;
	{UId,VId,admin} ->
		central_vendor
	end;

getLoginedInfo(L,vendor_mode) ->
	getLoginedInfo((session_service:getLoginRec(
						tools:get_param(L,"_inter_session_id","undefined")
					)),vendor_mode);

getLoginedInfo(L,T) ->
	session_service:getLoginedInfo(L,T).
ui_identity({name,L}) ->
	case user_service:get({id,session_service:getLoginedInfo(L,user_id)}) of 
	[U|_] ->
		U#user_rec.name;
	[] ->
		"错误用户信息"
	end;
ui_identity({register_name,L}) ->
	case vregister_service:get({id,session_service:getLoginedInfo(L,register_id)}) of 
	[] ->
		"错误注册信息";
	[U|_] ->
		U#v_register_rec.name
	end;
	
ui_identity(L) ->
	SessionId = tools:get_param(L,"_inter_session_id","undefined"),
	io:format("login session info ~p",[session_service:getLoginRec(SessionId)]),
	{ehtml,{'div',[],[
		{input,[{type,"hidden"},{id,"vendor_name"},{value,(session_service:getLoginRec(SessionId))#login_rec.vendor_name}],[]},
		{input,[{type,"hidden"},{id,"login_name"},{value,(session_service:getLoginRec(SessionId))#login_rec.login_name}],[]},
		{input,[{type,"hidden"},{id,"vendor_id"},{value,binary_to_list((session_service:getLoginRec(SessionId))#login_rec.vendor_id)}],[]}
	]}}.